package cn.client.data.remoteData.repository

import cn.client.data.remoteData.ApiService
import cn.client.data.remoteData.bean.BaseResp
import cn.client.data.remoteData.bean.UserBasicInfo
import cn.client.data.remoteData.bean.UserInfo
import cn.client.data.remoteData.bean.UserInfoCards
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import javax.inject.Inject

class UserRepository @Inject constructor(private val apiService: ApiService) {

    /**
     * 获取用户信息
     */
    suspend fun userInfo(uid: Int): BaseResp<UserInfo> {
        return apiService.userInfo(uid)
    }

    /**
     * 修改用户基础信息
     */
    suspend fun uploadUserBasicInfo(userBasicInfo: UserBasicInfo): BaseResp<Any> {
        return apiService.uploadUserBasicInfo(userBasicInfo)
    }

    /**
     * 登出
     */
    suspend fun logOut(uid: Int): BaseResp<Any> {
        return apiService.signOut(uid)
    }

    // 获取用户item
    suspend fun getUserItems(uid: Int): BaseResp<UserInfoCards>{
        return apiService.getUserCards(uid)
    }

    // 上传头像的方法
    suspend fun uploadAvatar(file: File, uid: Int): BaseResp<Any> {
        val filePart = createFilePart(file)
        val uidBody = uid.toRequestBody() // 转换为 RequestBody
        return apiService.uploadUserAvatar(filePart, uidBody)
    }

    // 转换为 RequestBody 的辅助方法
    private fun Int.toRequestBody(): RequestBody {
        return this.toString()
            .toRequestBody("text/plain".toMediaTypeOrNull())
    }

    // 用于封装MultipartBody.Part
    private fun createFilePart(file: File): MultipartBody.Part {
        val requestFile = file
            .asRequestBody("image/*".toMediaTypeOrNull())
        return MultipartBody.Part.createFormData("file", file.name, requestFile)
    }

}